<?php
namespace app\admin\controller\steward;
use app\admin\model\steward\AppsVersion;
use app\admin\model\system\Option;
use app\common\controller\Admin;
use app\common\annotation\NodeAnnotation;
use app\common\traits\ControllerCurd;
use think\Db;
use think\Request;

/**
 * Class Administrator
 * @NodeAnnotation(
 *     title="应用管理",
 *     parent="admin/steward.index/index",
 *     is_menu=0,
 *     is_view=0,
 *     auth=1,
 * )
 */
class Apps extends Admin
{
    use ControllerCurd;
    public $model;

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\steward\Apps();
    }

    /**
     * @NodeAnnotation(
     *     title="系统应用",
     *     parent="admin/steward.Apps",
     *     MenuRoot="admin/steward.index",
     *     is_menu = 1
     * )
     */
    public function index(Request $request)
    {
        $keywords  = $request->param("keywords");


        $apps = scan_dir(app_path() . '*', GLOB_ONLYDIR);
        $new_app_list =[];
        $search_app_list = [];
        $appList  = Option::where("option_name","like","%steward%")
            ->select()
            ->toArray();

        foreach ($apps as $app)
        {
            $app_file = app_path() . $app . DIRECTORY_SEPARATOR . 'app.json';

            $index = array_search('steward_'.$app,array_column($appList,"option_name"));

            if (file_exists($app_file))
            {
                if(isset($appList[$index]) && $appList[$index]['option_value']['name']==$app)
                {
                    $content = $appList[$index]['option_value'];
                }else{
                    $content = json_decode(file_get_contents($app_file),true);
                }
                array_push($new_app_list,$content);
            }
        }
        if($keywords)
        {
            foreach ($new_app_list as $v)
            {
                if($v['title']==$keywords)
                {
                    array_push($search_app_list,$content);
                }
            }
        }
        $this->assign([
            "appList" => $search_app_list?$search_app_list:$new_app_list,
            "search"  => [
                "keywords" => $keywords
            ]
        ]);
        return $this->fetch();
    }

    /**
     * @NodeAnnotation(
     *     title="系统应用设置",
     *     parent="admin/steward.Apps",
     *     MenuRoot="admin/steward.index",
     *     is_menu = 0
     * )
     */
    public function editapp(Request $request ,$id='')
    {
        $optionModel = new Option();

        $id = $id?$id:$request->param("id");

        $app = $optionModel->where("option_name","steward_".$id)->find();

        $new_app =[];

        if(!$app)
        {
            $app_file = app_path() . $id . DIRECTORY_SEPARATOR . 'app.json';
            if (file_exists($app_file))
            {
                $new_app = json_decode(file_get_contents($app_file),true);
            }
        }

        if($request->isPost() && $request->isAjax())
        {
            $input = $request->post();

            $app_info = [
                "option_name"  => "steward_".$id,
                "option_value" => $input['steward']
            ];

            if ($app)
            {
                $res = $optionModel->where("id",$app['id'])->update($app_info);
            }else{
                $res = $optionModel->create($app_info);
            }
            if($res)
            {
                $this->success("保存成功",url('admin/steward.apps/index'));
            }else{
                $this->error("保存失败");
            }
        }

        $this->assign([
            "app" => $app?$app['option_value']:$new_app,
        ]);

        return $this->fetch();
    }

    /**
     * @NodeAnnotation(
     *     title="应用商店",
     *     parent="admin/steward.Apps",
     *     MenuRoot="admin/steward.index",
     *     is_menu = 1
     * )
     */
    public function appshonp(Request $request)
    {
        $keywords  = $request->param("keywords");

        $where = [];

        if($keywords) array_push($where,['app_name',"like","%$keywords%"]);
        $this->assign([
            "appList" => $this->model->where($where)->paginate(),
            "search"  => [
                "keywords" => $keywords
            ]
        ]);
        return $this->fetch();
    }

    /**
     * @NodeAnnotation(
     *     title="添加应用",
     *     parent="admin/steward.Apps",
     *     MenuRoot="admin/steward.index",
     *     is_menu = 0
     * )
     */
    public function addapps()
    {
        $this->add(url('admin/steward.apps/appshonp'),function ($model,$res){


            //关联分类
            if(isset($res['category_id']) && !empty($res['category_id']))
            {
                $categoryIdList = explode(',',$res['category_id']);
                foreach ($categoryIdList as $v)
                {
                    //查重
                    $result = Db::name("apps_category_app")
                        ->where("category_id",$v)
                        ->where("post_id",$res['id'])
                        ->find();
                    if(!$result)
                    {
                        $result = Db::name("apps_category_app")->insert([
                            'post_id'     => $res['id'],
                            'category_id' => $v,
                            'list_order'  => 10000,
                            'status'      => 1
                        ]);
                    }
                    if($result)
                    {
                        (new \app\admin\model\steward\Category())->where("id",$v)->setInc("post_count");
                    }
                }
            }


            $model->where("id",$res['id'])->update([
                "app_keys"=>md5($res['app_name'])
            ]);

        });
        return $this->fetch();
    }

    /**
     * @NodeAnnotation(
     *     title="编辑应用",
     *     parent="admin/steward.Apps",
     *     MenuRoot="admin/steward.index",
     *     is_menu = 0
     * )
     */
    public function saveapps(Request $request,$id=0)
    {
        $post = $this->model->findData($id);

        $this->edit(url('admin/steward.apps/appshonp'),function($model,$data){
            //关联分类
            if(isset($data['category_id']) && !empty($data['category_id']))
            {
                $categoryIdList = explode(',',$data['category_id']);
                $cateResult = Db::name("apps_category_app")
                    ->where("post_id",$data['id'])
                    ->select();
                if($cateResult)
                {
                    Db::name("apps_category_app")
                        ->where("id",'in', array_column($cateResult,'id'))
                        ->delete();
                    (new \app\admin\model\steward\Category())->where("id",'in',array_column($cateResult,'category_id'))
                        ->where("post_count","neq",0)
                        ->setDec("post_count");
                }
                foreach ($categoryIdList as $v)
                {
                    //查重
                    $result = Db::name("apps_category_app")
                        ->where("category_id",$v)
                        ->where("post_id",$data['id'])
                        ->find();
                    if(!$result)
                    {
                        $result = Db::name("apps_category_app")->insert([
                            'post_id'     => $data['id'],
                            'category_id' => $v,
                            'list_order'  => 10000,
                            'status'      => 1
                        ]);
                    }
                    if($result)
                    {
                        (new \app\admin\model\steward\Category())->where("id",$v)->setInc("post_count");
                    }
                }
            }
        });

        //分类id 处理
        if(isset($post['category']))
        {
            $cateList = $post['category']->toArray();
            $post['categoryIdList'] = implode(',',array_column($cateList,'id'));
            $post['categoryNameLst'] = implode(',',array_column($cateList,'name'));
        }


        $this->assign([
            "apps"=> $post
        ]);

        return $this->fetch();
    }

    /**
     * @NodeAnnotation(
     *     title="删除应用",
     *     parent="admin/steward.Apps",
     *     MenuRoot="admin/steward.index",
     *     is_menu = 0
     * )
     */
    public function delapps(Request $request)
    {
        $this->del();
    }


    /**
     * @NodeAnnotation(
     *     title="应用发行包",
     *     parent="admin/steward.Apps",
     *     MenuRoot="admin/steward.index",
     *     is_menu = 0
     * )
     */
    public function appversion(Request $request,$app_id=0)
    {
        $keywords  = $request->param("keywords");

        $where = [];

        if($keywords) array_push($where,['app_version',"like","%$keywords%"]);

        array_push($where,['app_id','eq',$app_id]);

        $this->assign([
            "appVersionList" => (new AppsVersion())->selectPageDatas(1,20,$where),
            "app_id"         => $app_id,
            "search"         => [
                "keywords" => $keywords
            ]
        ]);
        return $this->fetch();
    }

    /**
     * @NodeAnnotation(
     *     title="添加应用发行包",
     *     parent="admin/steward.Apps",
     *     MenuRoot="admin/steward.index",
     *     is_menu = 0
     * )
     */
    public function addappversion($app_id=0)
    {
        $this->model = new AppsVersion();
        $this->add(url('admin/steward.apps/appversion',['app_id'=>$app_id]));
        $this->assign([
            "app_id" => $app_id
        ]);
        return $this->fetch();
    }


    /**
     * @NodeAnnotation(
     *     title="修改应用发行包",
     *     parent="admin/steward.Apps",
     *     MenuRoot="admin/steward.index",
     *     is_menu = 0
     * )
     */
    public function saveappversion($id = 0)
    {
        $this->model = new AppsVersion();
        $data = $this->model->findData($id);
        $this->edit(url('admin/steward.apps/appversion',['app_id'=>$data['app_id']]));
        $this->assign([
            "appversion" => $data
        ]);
        return $this->fetch();
    }
    /**
     * @NodeAnnotation(
     *     title="删除应用发行包",
     *     parent="admin/steward.Apps",
     *     MenuRoot="admin/steward.index",
     *     is_menu = 0
     * )
     */
    public function delappversion()
    {
        $this->model = new AppsVersion();
        $this->del();
    }
}